import { ProxyOb } from "./ProxyOb";
import VmBase, { StringFormat } from "./VmBase";

/*
 * @features: 功能
 * @description: 说明
 * @Date: 2021-09-07 22:23:15
 * @Author: judu233(769471424@qq.com)
 * @LastEditTime: 2021-09-14 13:33:44
 * @LastEditors: judu233
 */
const { ccclass, property, menu } = cc._decorator;

@ccclass
@menu('VM/VM-Progress')
export default class VmProgress extends VmBase {
    @property({
        visible() { return this.componentProperty === 'string' },
        tooltip: '字符串格式化，和 VMLabel 的字段一样，需要填入对应的格式化字符串'
    })
    stringFormat: string = '';
    
    @property({ displayName: `是否取整`, })
    isInt = true;


    /**代理对象 */
    proxy: ProxyOb<cc.Slider>['proxy'];

    checkCanWatch() {
        if (this.watchPathArr.length < 2) {
            console.error('VMProgress组件需要2个以上的参数');
            return false;
        }
        return super.checkCanWatch();
    }

    onValueInit() {
        try {
            if (this.controller) {
                this.node.on('slide', this.sliderChange, this);
                this.proxyOb.isCheckValue = false; 
            }
            //解析并设置
            this.watchPathArr.forEach((v, i) => this.templateValueArr[i] = ProxyOb.getValue(v));
            let value = this.templateValueArr[0] / this.templateValueArr[1];
            this.setComponentValue(value);
        } catch (err) {
            cc.error(`节点：${this.node.name}组件的VmProgress组件init失败`);
            cc.error(err);
        }
    }

    /**滑动轴改变 */
    sliderChange(slider: cc.Slider) {
        //通知这个节点上的代理对象
        this.proxy.progress = slider.progress;
    }

    /**设置组件值 */
    setComponentValue(value: any) {
        if (this.stringFormat !== '') {
            let res = StringFormat.deal(value, this.stringFormat);
            super.setComponentValue(res);
        } else {
            super.setComponentValue(value);
        }
    }

    /**组件值发生变动 */
    onValueController(n, o) {
        let value = n * this.templateValueArr[1];
        value = this.isInt ? Math.round(value) : value;
        if (Number.isNaN(value))
            value = 0;
        ProxyOb.setValue(this.watchPathArr[0], value);
    }

    /**初始化改变数据 */
    onValueChanged(n, o, path: string) {
        if (!this.useMultipathMode) return;
        //寻找缓存位置
        let index = this.watchPathArr.findIndex(v => v === path);
        if (index >= 0) {
            //如果是所属的路径，就可以替换文本了
            this.templateValueArr[index] = n; //缓存值
        }

        let value = this.templateValueArr[0] / this.templateValueArr[1];
        if (value > 1) value = 1;
        if (value < 0 || Number.isNaN(value)) value = 0;

        this.setComponentValue(value);
    }


}
